<template>
  <div class="user-manage-container">
    <el-card class="header">
      <el-row type="flex" justify="start">
        <el-col>
          <el-button type="primary" @click="handleAdd" v-permission="['importUser']">
            添加
          </el-button>
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            @click="handleRemove(null)"
          >
            删除
          </el-button>
        </el-col>
      </el-row>
    </el-card>
    <el-card>
      <el-table :data="tableData" border style="width: 100%" current-row-key="userId" @selection-change="handleUserSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="userName" :label="$t('msg.excel.name')">
        </el-table-column>
        <el-table-column prop="email" label="邮箱">
        </el-table-column>

        <el-table-column prop="age" label="年龄" align="center">

        </el-table-column>

        <el-table-column prop="gender" label="性别">

        </el-table-column>
        <el-table-column prop="phoneNum" label="手机号"></el-table-column>
        <el-table-column prop="avatarUrl" label="头像"></el-table-column>
        <el-table-column prop="address" label="地址"></el-table-column>
        <el-table-column prop="status" label="状态"></el-table-column>
        <el-table-column prop="lastLoginTime" label="最后登录时间"></el-table-column>
        <el-table-column prop="lastLoginIp" label="最后登录地址"></el-table-column>
        <el-table-column
          prop="action"
          label="操作"
          align="center"
          width="240"
          fixed="right"
          class-name="small-padding fixed-width"
          #default="{ row }">
          <el-space>
            <el-button @click="handleEdit(row)" size="small">修改</el-button>
            <el-button @click="handleRemove(row)" size="small" type="danger">删除</el-button>
            <el-button @click="handleRole(row)" size="small" type="success">分配角色</el-button>
          </el-space>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>


    <export-to-excel v-model="exportToExcelVisible"></export-to-excel>

    <div id="addAndUpdate">
      <el-dialog
        :title="title"
        v-model="visible"
        width="600px"
        append-to-body
        center
      >
        <el-form :ref="formRef" :model="form" label-width="80px">
          <!-- 用户名 -->
          <el-row>
            <el-col :span="12">
              <el-form-item prop="userName" label="用户名">
                <el-input v-model="form.userName"></el-input>
              </el-form-item>
            </el-col>
            <!-- 可能需要添加或删除这里的 el-form-item 根据需求 -->
          </el-row>

          <!-- 手机号、昵称 -->
          <el-row>
            <el-col :span="12">
              <el-form-item prop="phoneNum" label="手机号">
                <el-input v-model="form.phoneNum"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="nickName" label="昵称">
                <el-input v-model="form.nickName"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 邮箱、密码 -->
          <el-row>
            <el-col :span="12">
              <el-form-item prop="email" label="邮箱">
                <el-input v-model="form.email"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="password" label="密码">
                <el-input v-model="form.password"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 地址、状态 -->
          <el-row>
            <el-col :span="12">
              <el-form-item prop="address" label="地址">
                <el-input v-model="form.address"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="status" label="状态">
                <el-input v-model="form.status"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 性别、年龄 -->
          <el-row>
            <el-col :span="12">
              <el-form-item prop="sex" label="性别">
                <el-select v-model="form.sex" placeholder="请选择">
                  <el-option value="0" label="男" />
                  <el-option value="1" label="女" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="age" label="年龄">
                <el-input-number v-model="form.age"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 岗位、角色 -->
          <el-row>
            <el-col :span="12">
              <el-form-item prop="dept" label="岗位">
                <el-select v-model="form.dept" placeholder="请选择">
                  <el-option value="0" label="财务" />
                  <el-option value="1" label="人事" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="roleIds" label="角色">
                <el-select v-model="form.roleIds" multiple placeholder="请选择角色">
                  <el-option
                    v-for="item in roleList"
                    :key="item.roleId"
                    :label="item.roleName"
                    :value="item.roleId">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 描述 -->
          <el-row>
            <el-col :span="24">
              <el-form-item label="描述">
                <el-input type="textarea" v-model="form.description"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="submitForm">确认</el-button>
            <el-button @click="cancel">取消</el-button>
          </div>
        </template>
      </el-dialog>

      <el-drawer
        v-model="open"
        title="I have a nested table inside!"
        direction="rtl"
        size="30%"
        @open="handleOpen"
      >
        <el-table  row-key="roleId"   ref="tableRef" :data="roleList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="roleName" label="角色名" width="150" />
          <el-table-column prop="name" label="描述" width="160" />
        </el-table>
        <template #footer>
          <el-row>
            <el-space>
              <el-button @click="handleSubmit">确认</el-button>
              <el-button @click="handleCancel">取消</el-button>

            </el-space>
          </el-row>
        </template>
      </el-drawer>
    </div>
    <!--    <roles-dialog-->
    <!--      v-model="roleDialogVisible"-->
    <!--      :userId="selectUserId"-->
    <!--      @updateRole="getListData"-->
    <!--    ></roles-dialog>-->
  </div>
</template>

<script setup>
import { getCurrentInstance, nextTick, ref } from 'vue'
import { getUserManageList, getInfo, addUser, editUser ,deleteUser} from '@/api/user-manage'
import { addUserRole,getInfoByUserId } from '@/api/userRole'
import { list } from '@/api/role'
import { useRouter } from 'vue-router'
import ExportToExcel from './components/Export2Excel.vue'
const tableRef = ref()
import { ElMessageBox } from 'element-plus'

const tableData = ref([])
const page = ref(1)
const size = ref(5)
const total = ref(0)
const title = ref('')
const visible = ref(false)
const form = ref({
  userName: '',
  phoneNum: '',
  nickName: '',
  email: '',
  password: '',
  address: '',
  status: '',
  sex: '',
  age: 0,
  dept: '',
  roleId:'',
  roleIds: [],
  description: ''
})
const formRef = ref(null)
const open = ref(false)
const roleIds = ref([])
const userId = ref('')
const userIdS = ref([])
const { proxy } = getCurrentInstance();

/**
 * 查看角色的点击事件
 */
const selectUserId = ref('')
const roleDialogVisible = ref(false)
const router = useRouter()
const roleList = ref([])
const onShowRoleClick = row => {
  selectUserId.value = row._id
  roleDialogVisible.value = true
  console.log('分配角色', row, selectUserId.value)
}
// 获取数据的方法
const getListData = async () => {
  const { date } = await getUserManageList({
    page: page.value,
    size: size.value
  })
  console.table(date)

}

const getDataList = async () => {
  const response = await getUserManageList({
    page: page.value,
    size: size.value
  })
  const { data } = response
  tableData.value = data
  console.log(response)
}

const handleAdd = (row) => {
  debugger
  console.log('编辑数据', row.userId)
  visible.value = true
  title.value = '添加'
}
const handleEdit = (row) => {
  debugger
  console.log('编辑数据', row.userId)
  visible.value = true
  title.value = '修改'
  getInfo(row.userId).then(response=>{
    form.value=response.data
    console.table(response.data)
  })
}
const handleRemove =  (row) => {
  console.log("删除多个",userIdS.value)
  console.log(row)
  const ids = row? [ row.userId]:userIdS.value;
  console.log("删除ids：",ids)
  deleteUser(ids).then(response=>{
    console.log(response)
    getDataList()
  }).catch(err=>{}).finally(
    getDataList()
  )

};

const handleRole = (row) => {
  console.log('分配角色的用户', row)
  open.value = true
  userId.value = row.userId


}
const submitForm = () => {
  console.log(form.value.userName)
    if (form.value.userId != null){
      debugger
      editUser(form.value).then(response=>{
        const {message,code,data} = response
        if (code==200){
          proxy.$message.success(message);
        }else {
          proxy.$message.error(message);
        }

      })
    }else {
      addUser(form.value).then(response => {
        const {message,code,data} = response
        console.log(response)
        proxy.$message.success(message);
      })
    }

}
const cancel = () => {
  visible.value = false
  reset()
}
const handleSubmit = () => {
  debugger
  addUserRole(userId.value,roleIds.value).then(response=>{
    console.group()
    console.log('用户角色ids', roleIds.value)
    console.log('用户id', userId.value)
    console.groupEnd()
  })

}
const handleCancel = () => {
  open.value = false
}
const reset = () => {
  form.value = {}
}
const getRoleList = () => {
  list().then(response => {
    console.log('角色', response)
    const { data } = response
    roleList.value = data
    console.table(data)
  })


}
const handleOpen=()=>{

  list().then(response => {
    console.log('角色', response)
    const { data } = response
    roleList.value = data
    console.table(data)

  })

}


// 分页相关
/**
 * size 改变触发
 */
const handleSizeChange = currentSize => {
  size.value = currentSize
  getDataList()
}

/**
 * 页码改变触发
 */
const handleCurrentChange = currentPage => {
  page.value = currentPage
  getDataList()
}

const handleSelectionChange = (val) => {
  roleIds.value = val.map(item => item.roleId)
  console.log("选中的角色",roleIds.value)
}
const handleUserSelectionChange=(val)=>{
   userIdS.value=val.map(item => {return  item.userId})
  console.log( userIdS.value)
}
/**
 * excel 导入点击事件
 */
const onImportExcelClick = () => {
  router.push('/user/import')
}

/**
 * excel 导出点击事件
 */
const exportToExcelVisible = ref(false)



getDataList()
getRoleList()
</script>

<style lang="scss" scoped></style>
